<template>
  <view>
    <template v-if="modelValue.length > 0">
      <el-tag
        style="margin-left: 10px; cursor: pointer"
        v-for="(tag, idx) in modelValue"
        v-show="tag?.isShow ?? true"
        :key="tag.key"
        :type="tag?.type ?? ''"
        :effect="tag?.effect ?? 'plain'"
        class="mx-1"
        closable
        :disable-transitions="false"
        @click="onClickTag(tag, idx)"
        @close="handleClose(tag)"
      >
        {{ tag.label }}
      </el-tag>
    </template>
    <el-input
      v-if="inputVisible"
      ref="InputRef"
      v-model="inputValue"
      style="width: 120px; margin-left: 10px"
      class="ml-1 w-20"
      size="small"
      @keyup.enter="handleInputConfirm"
      @blur="handleInputConfirm"
    />
    <el-button
      v-else
      class="button-new-tag ml-1"
      style="margin-left: 10px"
      size="small"
      @click="showInput"
    >
      {{ addBtnName }}
    </el-button>
  </view>
</template>
<script setup>
import { nextTick, ref } from "vue";
import { getRandom, sampleSize } from "@gd-accbuild-core/config/utils";
const props = defineProps({
  modelValue: {
    type: Array,
    required: true,
  },
  addBtnName: {
    type: String,
    default: "+ 添加",
  },
});
const inputValue = ref("");
const inputVisible = ref(false);
const InputRef = ref(null);

const handleClose = (tag) => {
  const matchedIdx = props.modelValue.findIndex((el) => el.key === tag.key);
  props.modelValue.splice(matchedIdx, 1);
};

const showInput = () => {
  inputVisible.value = true;
  nextTick(() => {
    InputRef.value?.input?.focus();
  });
};

const colorTypes = ["", "info", "success", "danger", "warning"];
const handleInputConfirm = () => {
  if (inputValue.value) {
    const lastPickedTag = props.modelValue.find((el) => el.effect === "dark");
    if (lastPickedTag) {
      lastPickedTag.effect = "plain";
    }
    props.modelValue.push({
      label: inputValue.value,
      key: getRandom(),
      type: sampleSize(colorTypes, 1)[0],
      effect: "dark",
    });
  }
  inputVisible.value = false;
  inputValue.value = "";
};
const emits = defineEmits(["clickTag", "update:modelValue"]);
const onClickTag = (tag, idx) => {
  const lastPickedTag = props.modelValue.find((el) => el.effect === "dark");
  if (lastPickedTag) {
    lastPickedTag.effect = "plain";
  }
  if (!lastPickedTag || lastPickedTag.key !== tag.key) {
    tag.effect = "dark";
    emits("clickTag", { tag: tag, idx });
  }
};
</script>
